package com.qf.business.auth.controller;

import com.ken.event.action.apply.producer.EventTemplate;
import com.qf.commons.base.result.R;
import com.qf.commons.base.result.Rs;
import com.qf.data.notify.entity.Email;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotBlank;
import java.util.concurrent.TimeUnit;

/**
 * author Ken
 * create_time 2022/11/24
 */
@RestController
@RequestMapping("/auth/code")
@Validated
@Slf4j
public class CodesController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 发送邮箱的验证码
     * @return
     */
    @RequestMapping("/send")
    public R sendEmailCode(@NotBlank(message = "邮箱不能为空！") String email){
        log.debug("[email code send] 给指定邮箱发送验证码 - {}", email);

        //生成验证码 4位 1000~9999 [1000~10000)
        String code = (int)(Math.random() * 9000 + 1000) + "";
//        String code = "1234";

        //将发送的验证码保存起来
        redisTemplate.opsForValue().set(email, code, 5, TimeUnit.MINUTES);

        //组装一个邮件的对象 -> 发送给通知服务进行邮件的发送
        Email emailObj = new Email()
                .setSubject("[官方邮件]千锋在线教育平台")
                .addTo(email)
                .setContent("当前登录的验证码为：" + code + "，如果不是本人操作请忽略！");

        //告知通知服务发送邮件
        EventTemplate.sendQuickly("email-code", emailObj);

        return Rs.create();
    }
}
